package com.cmict.data.system.service.conf;

import cn.hutool.http.HtmlUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmict.data.framework.common.enums.ConfKeyEnum;
import com.cmict.data.framework.common.pojo.PageResult;
import com.cmict.data.framework.security.core.util.AESUtil;
import com.cmict.data.framework.security.core.util.RSAUtils;
import com.cmict.data.system.controller.admin.conf.vo.*;
import com.cmict.data.system.convert.conf.ConfConvert;
import com.cmict.data.system.dal.dataobject.conf.ConfDO;
import com.cmict.data.system.dal.mysql.conf.ConfMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

import static com.cmict.data.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cmict.data.system.enums.ErrorCodeConstants.CONF_NOT_EXISTS;


/**
 * 系统通用配置信息 Service 实现类
 *
 * @author liutao
 * @date 2022/4/22
 */
@Service
@Validated
public class ConfServiceImpl implements ConfService {

    @Resource
    private ConfMapper confMapper;

    @Override
    public Long createConf(ConfCreateReqVO createReqVO) {
        // 插入
        ConfDO conf = ConfConvert.INSTANCE.convert(createReqVO);
        confMapper.insert(conf);
        // 返回
        return conf.getId();
    }

    /**
     * 获取 对应的值
     * @param confKey
     * @return
     */
    @Override
    public ConfSystem getConfValueByConfKey(String confKey){
        ConfSystem result = null;
        ConfDO  confDO = new ConfDO();
        JSONObject jsonObject = new JSONObject();
        switch (confKey){
           case  "system_safe":
                confDO = confMapper.selectOne("conf_key", confKey);
                result = JSONObject.parseObject(confDO.getConfValue(), ConfSystem.class);

              break;
           case  "system_email":
               confDO = confMapper.selectOne("conf_key", confKey);
               result = JSONObject.parseObject(confDO.getConfValue(), ConfSystem.class);
               break;
        }
        return result;

    }

    @Override
    public void updateConf(ConfUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateConfExists(updateReqVO.getId());
        updateReqVO.setConfKey(HtmlUtil.filter(updateReqVO.getConfKey()));
        updateReqVO.setDescription(HtmlUtil.filter(updateReqVO.getDescription()));
        updateReqVO.setType(HtmlUtil.filter(updateReqVO.getType()));
        // 更新
        ConfDO updateObj = ConfConvert.INSTANCE.convert(updateReqVO);
        if(updateObj.getConfKey().equals(ConfKeyEnum.SYSTEM_EMAIL.getConfKey())){
            ConfSystem confValueByConfKey = JSONObject.parseObject(updateObj.getConfValue(), ConfSystem.class);
            if(null != confValueByConfKey && null != confValueByConfKey.getEmailPassword()){
                String password = RSAUtils.decrypt(confValueByConfKey.getEmailPassword());
                if(!password.startsWith(AESUtil.ENCRYPT_FLAG)){
                    confValueByConfKey.setEmailPassword(AESUtil.ENCRYPT_FLAG + AESUtil.encrypt(password));
                    JSONObject jsonObject = (JSONObject) JSONObject.toJSON(confValueByConfKey);
                    updateObj.setConfValue(jsonObject.toString());
                }
            }
        }
        confMapper.updateById(updateObj);
    }

    @Override
    public void deleteConf(Long id) {
        // 校验存在
        this.validateConfExists(id);
        // 删除
        confMapper.deleteById(id);
    }

    private void validateConfExists(Long id) {
        if (confMapper.selectById(id) == null) {
            throw exception(CONF_NOT_EXISTS);
        }
    }

    @Override
    public ConfDO getConf(Long id) {
        return confMapper.selectById(id);
    }

    @Override
    public List<ConfDO> getConfList(Collection<Long> ids) {
        return confMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ConfDO> getConfPage(ConfPageReqVO pageReqVO) {
        return confMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ConfDO> getConfList(ConfExportReqVO exportReqVO) {
        return confMapper.selectList(exportReqVO);
    }

    @Override
    public ConfDO getByKey(String keyName) {
        return confMapper.selectOne(ConfDO::getConfKey,keyName);
    }

    @Override
    public List<ConfDO> getConfListByconfKey(String confKey) {
        List<ConfDO> list = confMapper.selectList(new QueryWrapper<ConfDO>()
                .eq(StringUtils.isNotBlank(confKey), "conf_Key", confKey)
        );

        return list;
    }

    @Override
    public ConfDO getLoginConf(String confKey) {
       ConfDO confDO = confMapper.selectOne(new QueryWrapper<ConfDO>()
                .eq(StringUtils.isNotBlank(confKey), "conf_Key", confKey)
        );

        return confDO;
    }
}
